package com.heima.user.service.impl;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Autowired
    private ApUserMapper userMapper;
    @Override
    public ResponseResult login(LoginDto dto) {
        String password = dto.getPassword();
        String phone = dto.getPhone();
        if(StringUtils.isNotEmpty(password)&&StringUtils.isNotEmpty(phone)){
//            根据电话号码查询数据库
            ApUser user = userMapper.selectOne(new LambdaQueryWrapper<ApUser>().eq(ApUser::getPhone, phone));
            if(user==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户未注册");
            }
//            用户数据对比
            String salt = user.getSalt();
            String password1 = user.getPassword();
//            加密前端传过来的密码
            String pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if(!password1.equals(pwd)){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
//            密码正确返回jwt
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(user.getId().longValue()));
            user.setPassword("");
            user.setSalt("");
            map.put("user",user);
            return ResponseResult.okResult(map);
        }
        else {
//            游客同样返回token  id=0；
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }
}
